import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL,
  timeout: 10000
})

let loadingInstance

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 显示loading
    loadingInstance = ElLoading.service({ fullscreen: true })
    
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['x-token'] = token
    }
    return config
  },
  error => {
    loadingInstance?.close()
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    loadingInstance?.close()
    const res = response.data
    
    // 如果返回的状态码不是200，说明接口请求有误
    if (res.__sys__ && res.__sys__.status !== 1) {
      ElMessage.error(res.__sys__.msg || '请求失败')
      return Promise.reject(new Error(res.__sys__.msg || '请求失败'))
    }
    
    return res
  },
  error => {
    loadingInstance?.close()
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

export default service